package cn.edu.anan.fun;

import java.util.Comparator;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
 * 函数式编程示例代码
 *
 * @author ThinkPad
 * @version 1.0
 * @date 2022/1/2 11:43
 */
public class FunctionDemo {

    public static void main(String[] args) {
        Optional<Integer> min = Stream.of("cat", "dog", "pig", "monster", "tiger", "dragLong")
                .map(v -> v.length())
                .filter(l -> l <= 3)
                .min((o1, o2) -> o1 - o2);
        System.out.println("计算结果：" + min.orElse(0));

        Optional<Integer> min2 = Stream.of("cat", "dog", "pig", "monster", "tiger", "dragLong")
                .map(new Function<String, Integer>() {
                    @Override
                    public Integer apply(String s) {
                        return s.length();
                    }
                })
                .filter(new Predicate<Integer>() {
                    @Override
                    public boolean test(Integer i) {
                        return i <= 3;
                    }
                })
                .min(new Comparator<Integer>() {
                    @Override
                    public int compare(Integer o1, Integer o2) {
                        return o1 - o2;
                    }
                });
        System.out.println("计算结果：" + min2.orElse(0));
    }
}
